package com.winit.openapi.ece.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.oms.spi.ece.EcePrintLabelService;
import com.winit.oms.spi.ece.command.EcePrintLabelCommand;
import com.winit.oms.spi.isp.vo.ISPLabel;
import com.winit.oms.spi.vo.Label;
import com.winit.oms.spi.vo.LabelInfo;
import com.winit.oms.spi.vo.PrintLabelResult;
import com.winit.oms.spi.vo.PrintLabelResult.Result;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.ece.vo.TrackingNo;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.PDFBox4MergePDF;
import com.winit.openapi.util.ValidateUtil;
import com.winit.openapi.util.WinitLabelParser;
import com.winit.openapi.controller.BaseController;

/**
 *打印面单
 * 
 * @version <pre>
 * Author	  Version		Date		Changes
 * dinghua.an	1.0  		2015年8月3日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/ece/label")
public class LabelController extends BaseController {

    private Logger               logger = LoggerFactory.getLogger(LabelController.class);
    @Resource
    private EcePrintLabelService ecePrintLableService;

    /**
     * OpenAPI打印面单，获取到文件地址后用64base编码
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        EcePrintLabelCommand labelCommand = null;
        Object obj = requestMsg.getData();
        String isReturnFiles = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            valiLabelParms(json);
            isReturnFiles = json.getString("isReturnFiles");
            labelCommand = new EcePrintLabelCommand();
            this.buildLabelCommand(json, labelCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        List<ISPLabel> labels = labelCommand.getiSPLabel();
        // result
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> files = new ArrayList<String>();
        List<TrackingNo> tList = new ArrayList<TrackingNo>();

        if (labels.size() == 1) {
            WinitLabelParser parser = new WinitLabelParser();
            LabelInfo labelInfo = ecePrintLableService.printLabel(labelCommand);
            List<Label> labList = labelInfo.getLabelList();
            for (Label lab : labList) {
                if (lab.getPrintQty() > 1) {
                    List<String> labelPath = new ArrayList<String>();
                    for (int i = 0; i < lab.getPrintQty(); i++) {
                        labelPath.add(lab.getFilePath());
                    }
                    files = mergeLabels(labelPath);
                } else {
                    files.add(parser.getWinitLabelByURL(lab.getFilePath()));
                }

                TrackingNo tn = new TrackingNo();
                tn.setTrackingNo(lab.getTrackingNo());
                tList.add(tn);
            }
        } else if (labels.size() > 1) {
            // 批量打印面单
            PrintLabelResult labelInfo = ecePrintLableService.multilPrintLabel(labelCommand);
            List<Result> results = labelInfo.getResult();
            for (Result r : results) {
                List<Label> list = r.getLabelList();
                for (Label label : list) {
                    TrackingNo tn = new TrackingNo();
                    tn.setTrackingNo(label.getTrackingNo());
                    tList.add(tn);
                }
            }

            List<String> labelPath = labelInfo.getLabelPath();
            files = mergeLabels(labelPath);
            dataMap.put("successCount", labelInfo.getSuccess());
            dataMap.put("failedCount", labelInfo.getFailed());
        }
        if ("Y".equals(isReturnFiles)||isReturnFiles==null) {
            dataMap.put("files", files);
        } else {
            dataMap.put("trackingNoList", tList);
        }
        responseMsg.setData(dataMap);
        return SUCCESS;
    }

    /**
     * 多面单合并成一个PDF
     * 
     * @param labelPaths 面单URL
     * @return
     */
    private List<String> mergeLabels(List<String> labelPaths) {
        List<String> files = null;
        if (null != labelPaths && labelPaths.size() > 0) {
            files = new ArrayList<String>();
            PDFBox4MergePDF tool = new PDFBox4MergePDF();
            String path = "";
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                path = ApiConstant.PATH_MERGE_PDF_WIN + DateUtil.getCurrentDate() + ".pdf";
            } else {
                path = ApiConstant.PATH_MERGE_PDF_LINUX + DateUtil.getCurrentDate() + ".pdf";
            }
            try {
                tool.merge(labelPaths, path);
                files.add(tool.file2Base64(path));
            } catch (Exception e) {
                logger.error("WinitLableController->query :error:{}", e.getLocalizedMessage());
            } finally {
                // 删除临时文件
                tool.delFile(path);
            }
        }
        return files;
    }

    /**
     * ECE 封装打印面单参数
     * 
     * @param json
     * @param command
     */
    private void buildLabelCommand(JSONObject json, EcePrintLabelCommand command) {
        if (StringUtils.isNotBlank(json.getString("orderNoList"))) {
            JSONArray orderNoList = json.getJSONArray("orderNoList");
            List<ISPLabel> labels = new ArrayList<ISPLabel>();
            for (Object o : orderNoList) {
                JSONObject orderNO = (JSONObject) o;
                ISPLabel ispLabel = new ISPLabel();
                ispLabel.setOrderNO(orderNO.getString("orderNo"));
                labels.add(ispLabel);
            }
            command.setiSPLabel(labels);
            command.setIsReturnFiles(json.getString("isReturnFiles"));
        }
    }

    /**
     * 校验打印面单参数
     * 
     * @param json
     */
    private void valiLabelParms(JSONObject json) {
        JSONArray orderNoList = json.getJSONArray("orderNoList");
        ValidateUtil.validNotNull(json, "orderNoList");
        ValidateUtil.validList(json, "orderNoList");
        for (Object o : orderNoList) {
            JSONObject orderNO = (JSONObject) o;
            ValidateUtil.validNotNull(orderNO, "orderNo");
            ValidateUtil.validMaxLength(orderNO, "orderNo", 32);
        }
        ValidateUtil.validMaxLength(json, "isReturnFiles", 10);
    }
}
